﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace zx
{
	/// <summary>
	/// 诛仙15职业类
	/// </summary>
	public class GShop15
	{
		public GShop15()
		{
			ItemList = new List<Item>();
			FirstClassList = new List<FirstClass>();
		}

		/// <summary>
		/// 清空类里面的类容
		/// </summary>
		public void Clear()
		{
			TimeStamp = 0;
			GoodsCount = 0;
			ItemList.Clear();
			FirstClassCount = 0;
			FirstClassList.Clear();
		}

		/// <summary>
		/// 加载GShop文件
		/// </summary>
		/// <param name="filePath"></param>
		public void Load(string filePath)
		{

			FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
			Load(fs);
		}
		
		/// <summary>
		/// 从流读取GShop结构
		/// </summary>
		/// <param name="fileStream"></param>
		public void Load(Stream fileStream)
		{
			fileStream.Seek(0, SeekOrigin.Begin);
			BinaryReader reader = new BinaryReader(fileStream,Encoding.Unicode);

			this.Clear();
			// 开始读取文件数据
			try
			{
				this.TimeStamp = reader.ReadInt32();
				this.GoodsCount = reader.ReadInt32();
				// 循环读取ITEM结构
				for (Int32 i = 0; i < this.GoodsCount; i++)
				{

					Item goodsItem = new Item();

					goodsItem.ID = reader.ReadInt32();
					goodsItem.Count = reader.ReadInt32();
					goodsItem.IconPath = reader.ReadBytes(128);
					goodsItem.Price = reader.ReadInt32();
					goodsItem.TimeLimit = reader.ReadInt32();
					goodsItem.PriceDiscount = reader.ReadInt32();
					goodsItem.PriceRebate = reader.ReadInt32();
					goodsItem.IsNew = reader.ReadByte();
					goodsItem.IsBind = reader.ReadByte();
					goodsItem.Tools = reader.ReadInt16();
					goodsItem.Class1 = reader.ReadInt32();
					goodsItem.Class2 = reader.ReadInt32();
					goodsItem.Order = reader.ReadInt32();
					goodsItem.Description = reader.ReadBytes(1024);
					goodsItem.Name = reader.ReadBytes(64);
					goodsItem.IsAward = reader.ReadByte();
					goodsItem.AwardName = reader.ReadBytes(64);
					goodsItem.AwardID = reader.ReadInt32();
					goodsItem.AwardCount = reader.ReadInt32();
					goodsItem.AwardTimeLimit = reader.ReadInt32();
					goodsItem.AwardIconPath = reader.ReadBytes(128);
					goodsItem.IsAwardBind = reader.ReadBoolean();
					goodsItem.AwardDescription = reader.ReadBytes(1024);
					goodsItem.Type = reader.ReadInt32();
					goodsItem.BeginTime = reader.ReadInt32();
					goodsItem.EndTime = reader.ReadInt32();
					goodsItem.Unknow1 = reader.ReadInt32();
					goodsItem.SearchKeyWords = reader.ReadBytes(128);

					ItemList.Add(goodsItem);

				}

				this.FirstClassCount = reader.ReadInt32();
				// 循环读取FisrtClass结构
				for (Int32 j = 0; j < this.FirstClassCount; j++)
				{
					FirstClass firstClass = new FirstClass();
					firstClass.FirstClassID = reader.ReadInt32();
					firstClass.FirstClassName = reader.ReadBytes(128);
					firstClass.SecondClassCount = reader.ReadInt32();

					//循环读取SecondClass结构
					for (Int32 k = 0; k < firstClass.SecondClassCount; k++)
					{
						byte[] secondClassName = new byte[128];
						secondClassName = reader.ReadBytes(128);
						firstClass.SecondClassNameList.Add(secondClassName);
					}

					this.FirstClassList.Add(firstClass);
				}
				reader.Close();
			}
			catch (Exception e)
			{

				throw e;
			}

		}
		/// <summary>
		/// 保存文件
		/// </summary>
		/// <param name="filePath"></param>
		public void Save(string filePath)
		{
			FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite);
			Save(fs);
		}

		/// <summary>
		/// 从流保存文件
		/// </summary>
		/// <param name="fileStream"></param>
		public void Save(Stream fileStream)
		{
			fileStream.Seek(0, SeekOrigin.Begin);
			BinaryWriter writer = new BinaryWriter(fileStream,Encoding.Unicode);

			//开始写入文件
			writer.Write(TimeStamp);
			writer.Write(GoodsCount);
			foreach (var item in ItemList)
			{
				writer.Write(item.ID);
				writer.Write(item.Count);
				writer.Write(item.IconPath, 0, 128);
				writer.Write(item.Price);
				writer.Write(item.TimeLimit);
				writer.Write(item.PriceDiscount);
				writer.Write(item.PriceRebate);
				writer.Write(item.IsNew);
				writer.Write(item.IsBind);
				writer.Write(item.Tools);
				writer.Write(item.Class1);
				writer.Write(item.Class2);
				writer.Write(item.Order);
				writer.Write(item.Description, 0, 1024);
				writer.Write(item.Name, 0, 64);
				writer.Write(item.IsAward);
				writer.Write(item.AwardName, 0, 64);
				writer.Write(item.AwardID);
				writer.Write(item.AwardCount);
				writer.Write(item.AwardTimeLimit);
				writer.Write(item.AwardIconPath, 0, 128);
				writer.Write(item.IsAwardBind);
				writer.Write(item.AwardDescription, 0, 1024);
				writer.Write(item.Type);
				writer.Write(item.BeginTime);
				writer.Write(item.EndTime);
				writer.Write(item.Unknow1);
				writer.Write(item.SearchKeyWords, 0, 128);
			}

			writer.Write(FirstClassCount);
			foreach (var firstClass in FirstClassList)
			{
				writer.Write(firstClass.FirstClassID);
				writer.Write(firstClass.FirstClassName, 0, 128);
				writer.Write(firstClass.SecondClassCount);

				foreach (var secondClass in firstClass.SecondClassNameList)
				{
					writer.Write(secondClass, 0, 128);
				}
			}

			writer.Close();
		}

		public static void VerifyVersion(string filePath)
		{
			FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
			VerifyVersion(fs);
		}

		/// <summary>
		/// 版本识别，错误返回False，并抛出异常
		/// </summary>
		/// <param name="fileStream"></param>
		/// <returns></returns>
		public static void VerifyVersion(Stream fileStream)
		{
			fileStream.Seek(0, SeekOrigin.Begin);
			BinaryReader reader = new BinaryReader(fileStream, Encoding.Unicode);

			int header = reader.ReadInt32();
			int itemCount = reader.ReadInt32();
			
			// ITEM 结构体一共有2630字节，先判断剩下部分长度够不够填充ItemList
			if(2630*itemCount>=(fileStream.Length-4-4))
			{
				throw new Exception("此GShop.data不是15职业版本！");
			}

		}


		/// <summary>
		/// 通过ID获取Item
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public Item GetItemByID(int id)
		{
			foreach (var item in ItemList)
			{
				if (item.ID == id)
				{
					return item;
				}
			}
			throw new Exception("不存在的ID！");
		}

		/// <summary>
		/// 根据Name获取Item
		/// </summary>
		/// <param name="name"></param>
		/// <returns></returns>
		public Item GetItemByName(string name)
		{
			foreach (var item in ItemList)
			{
				string nameStr = System.Text.Encoding.Unicode.GetString(item.Name).TrimEnd('\0');
				if ( nameStr == name) 
				{
					return item;
				}
			}
			throw new Exception("不存在的Name！");
		}

		/// <summary>
		/// 时间戳
		/// </summary>
		public int TimeStamp { get; set; }

		///<summary>
		///	商品总数
		/// </summary>
		public int GoodsCount { get; set; }

		///<summary>
		///	商品列表
		/// </summary>
		public List<Item> ItemList { get; set; }

		///<summary>
		/// 商品大类总数
		/// </summary>
		public int FirstClassCount { get; set; }

		///<summary>
		///	商品大类列表
		/// </summary>
		public List<FirstClass> FirstClassList { get; set; }

		/// <summary>
		/// FirstClass为商品大分类
		/// </summary>
		public class FirstClass
		{
			public FirstClass()
			{
				FirstClassID = new int();
				FirstClassName = new byte[128];
				SecondClassCount = new int();
				SecondClassNameList = new List<byte[]>();
			}

			/// <summary>
			/// 商品大分类的ID
			/// </summary>
			public int FirstClassID { get; set; }

			/// <summary>
			/// 商品大类名称
			/// </summary>
			public byte[] FirstClassName { get; set; }

			/// <summary>
			/// 商品小分类的总数
			/// </summary>
			public int SecondClassCount { get; set; }

			/// <summary>
			/// 商品小分类列表
			/// </summary>
			public List<byte[]> SecondClassNameList { get; set; }
		}

		///<summary>
		/// 商品结构
		/// </summary>
		public class Item
		{
			public Item()
			{
				IconPath = new byte[128];
				Description = new byte[1024];
				Name = new byte[64];
				AwardName = new byte[64];
				AwardIconPath = new byte[128];
				AwardDescription = new byte[1024];
				SearchKeyWords = new byte[128];
			}
			public Int32 ID { get; set; }
			public Int32 Count { get; set; }             //数量
			public byte[] IconPath { get; set; }        //图标路径
			public Int32 Price { get; set; }             //价格
			public Int32 TimeLimit { get; set; }         //时限制
			public Int32 PriceDiscount { get; set; }     //折扣
			public Int32 PriceRebate { get; set; }      //返利倍数
			public byte IsNew { get; set; }             //是否新品
			public byte IsBind { get; set; }            //是否绑定
			public short Tools { get; set; }            //未知
			public Int32 Class1 { get; set; }            //大分类
			public Int32 Class2 { get; set; }            //小分类
			public Int32 Order { get; set; }             //顺序
			public byte[] Description { get; set; }      //描述
			public byte[] Name { get; set; }             //名称
			public byte IsAward { get; set; }            //是否有赠品
			public byte[] AwardName { get; set; }        //赠品名
			public Int32 AwardID { get; set; }           //赠品ID
			public Int32 AwardCount { get; set; }           //赠品
			public Int32 AwardTimeLimit { get; set; }       //赠品时限
			public byte[] AwardIconPath { get; set; }       //赠品图标路径
			public bool IsAwardBind { get; set; }           //赠品是否绑定
			public byte[] AwardDescription { get; set; }    //赠品描述
			public Int32 Type { get; set; }                 //类型、
			public Int32 BeginTime { get; set; }            //开始时间
			public Int32 EndTime { get; set; }              //结束时间
			public Int32 Unknow1 { get; set; }                //未知
			public byte[] SearchKeyWords { get; set; }       //搜索关键词

		}
	}
}
